package com.eltonkent.dashboard.service.responsehandler;

import java.io.IOException;
import java.io.InputStream;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.eltonkent.dashboard.data.container.WeatherContainer;
import com.eltonkent.dashboard.util.logger.Logger;

public class YahooWeatherHandler extends XmlHandler {
	private static final String TAG_UNITS = "units";
	private static final String TAG_WIND = "wind";
	private static final String TAG_ATMOSPHERE = "atmosphere";
	private static final String TAG_ASTRO = "astronomy";
	private static final String TAG_CONDITION = "condition";

	@Override
	public WeatherContainer deserialize(InputStream is) {
		try {
			XmlPullParser parser = getParser(is);
			String tagName;
			int eventType = parser.getEventType();
			WeatherContainer container = new WeatherContainer();
			for (; eventType != XmlPullParser.END_DOCUMENT;) {
				if (eventType == XmlPullParser.START_TAG) {
					tagName = parser.getName();
					Logger.i("TAG", "Tag Found name=>" + tagName);
					if (tagName.equals(TAG_UNITS)) {
						container.setTempScale(parser.getAttributeValue(0));
						container.setPressureScale(parser.getAttributeValue(2));
						container.setWindScale(parser.getAttributeValue(3));
					} else if (tagName.equals(TAG_WIND)) {
						container.setYahooWindDirection(parser
								.getAttributeValue(1));
						container.setYahooWindCondition(parser
								.getAttributeValue(1));
					} else if (tagName.equals(TAG_ATMOSPHERE)) {
						container.setYahooHumidity(parser.getAttributeValue(0));
						container.setPressure(parser.getAttributeValue(2));
					} else if (tagName.equals(TAG_ASTRO)) {
						container.setSunrise(parser.getAttributeValue(0));
						container.setSunset(parser.getAttributeValue(1));
					} else if (tagName.equals(TAG_CONDITION)) {
						container.setWeatherCondition(parser
								.getAttributeValue(0));
						
						container.setYahooTemperature(parser
								.getAttributeValue(2));
						break;
					}
				}
				eventType = parser.next();
			}
			is.close();
			return container;
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

}
